import { LocalUser } from "@/users/local-user";
import $ from "jquery";
import * as bootstrap from "bootstrap";
import { MessageBox } from "@/modules/components/dialog";
import { Loading } from "@/modules/components/loading";
import Task from "@/utils/task";
import { onDeviceHostSelected, SelectOption } from "../components/select";
import { HttpClient } from "@/utils/http-client";
import { DevicePartResponse } from "../../tyeps/device-part-response";
import { String } from "@/utils/string";
import { CurrentSaveInfo } from "../components/select";
import type { DeviceMaintenanceResponse } from "../../tyeps/device-maintenance-response";

// 输入对话框
const baseUrl = process.env.DEVICE_OPS_SERVICE_API_BASE_URL;

type DeviceMaintenance = {
  device: DeviceMaintenanceResponse;
  parts: DevicePartResponse[];
};

export interface PageViewModel {
  processName: string;
  deviceMaintenanceList: DeviceMaintenance[];
  deviceHostId: string;
  deviceHostName: string;
}

const url = new URL(window.location.href);
const parameters = new URLSearchParams(url.search);
const mixingProcess = parameters.get("process");

export type FetchDataCallback = (viewModel: PageViewModel) => void;

export class PageContext {
  private static callbackList = new Set<FetchDataCallback>();

  static onLoaded(callback: FetchDataCallback) {
    PageContext.callbackList.add(callback);
  }

  static invoke(viewModel: PageViewModel) {
    PageContext.callbackList.forEach((callback) => {
      callback(viewModel);
    });
  }
}

const viewModel: PageViewModel = {
  processName: "",
  deviceMaintenanceList: [],
  deviceHostId: "",
  deviceHostName: "",
};

onDeviceHostSelected(async (option: SelectOption) => {
  viewModel.deviceHostId = option.value;
  viewModel.deviceHostName = option.label;
});

async function loadDataAsync() {
  Loading.Open("正在加载数据...");
  try {
    const httpClient = new HttpClient();
    const deviceList = await httpClient.getAsync<DeviceMaintenanceResponse[]>(
      baseUrl +
        "/device-hosts/" +
        viewModel.deviceHostId +
        "/device-maintenances"
    );

    for (let index = 0; index < deviceList.length; index++) {
      const parts = await httpClient.getAsync<DevicePartResponse[]>(
        baseUrl + "/device-maintenances/" + deviceList[index].id + "/parts"
      );
      const tempDevice: DeviceMaintenance = {
        device: deviceList[index],
        parts: parts,
      };
      viewModel.deviceMaintenanceList.push(tempDevice);
    }
  } catch (err) {
    console.log(err);
    MessageBox.ShowNitification("错误提示", "加载工序数据错误！");
    Loading.Close();
    return;
  } finally {
    if (viewModel.deviceMaintenanceList.length > 0)
      $("#device-count-text")?.html(
        `${viewModel.deviceMaintenanceList.length.toString()}<span>个</span>`
      );

    // 搅拌工序
    if (mixingProcess === "mixing") {
      viewModel.processName = "mixing";
      $("#chart_3").attr(
        "style",
        "width: 100%; height: 22.30rem; background: url(./img/anode-mixing.png) no-repeat; background-size: auto 90%; background-position: center top;"
      );
      $("#process-title").text("搅拌工序-搅拌机");
    } else {
      viewModel.processName = "pulping";
      $("#chart_3").attr(
        "style",
        "width: 100%; height: 22.30rem; background: url(./img/pulping-machine.png) no-repeat; background-size: auto 90%; background-position: center top;"
      );
      $("#process-title").text("搅拌工序-制浆机");
    }

    PageContext.invoke(viewModel);
    await Task.waitAsync(1000);
    Loading.Close();
  }

  let count = 0;
  viewModel.deviceMaintenanceList.forEach((item) => {
    count += item.parts.length;
  });

  $("#jump-devcie-link").attr(
    "href",
    "/cardboards/" +
      viewModel.processName +
      "?deviceId=" +
      viewModel.deviceHostId
  );
  $("#device-host-id-text").text(viewModel.deviceHostName);
  $("#device-maintenance-count-text").text(viewModel.deviceMaintenanceList.length);
  $("#device-part-count-text").text(count);
  $("#exception-count-text").text("--");
  $("#notification-count-text").text("--");
  $("#warning-count-text").text("--");
}

$(async () => {
  const userInfo = LocalUser.tryGetUserInfo();

  if (userInfo == null) {
    MessageBox.ShowNitification("提示", "用户未登录！");
    return;
  }

  const currentSaveInfoString = localStorage.getItem(
    "mixing-machine-save-info"
  );

  if (String.isNullOrWhitespace(currentSaveInfoString)) {
    const element = $("#selectInputModal").get(0);
    if (element != null) {
      const modal = new bootstrap.Modal(element);
      modal.show();
    }
  } else {
    const obj = JSON.parse(currentSaveInfoString!) as CurrentSaveInfo;
    viewModel.deviceHostId = obj.currentDeviceHostId;
    viewModel.deviceHostName = obj.currentDeviceHostName;

    await loadDataAsync();
  }

  $("#selectDeviceHostButton").on("click", async () => {
    await loadDataAsync();
  });
});
